import 'dart:async';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import '../bean/app_response.dart';
import '../bean/articles_bean.dart';
import '../bean/banner_bean.dart';
import '../network/api.dart';
import '../network/request_util.dart';
import '../utils/log_util.dart';

class HomeController extends GetxController {
  var bannerList = <BannerBean>[].obs;
  var articleList = <ArticleBean>[].obs;
  var _pageIndex = 0;

  final controller = EasyRefreshController(
      controlFinishRefresh: true, controlFinishLoad: true);

  final scrollController = ScrollController();

  @override
  Future<void> onInit() async {
    super.onInit();
    await getBannerList();
    refreshRequest();
  }

  /// 下拉刷新请求，页面值为0，清空banner，article集合数据
  void refreshRequest() async {
    _pageIndex = 0;
    articleList.clear();
    var topArticlesOk = await getTopArticlesList();
    var articlesOk = await getArticlesList();
    if (articlesOk == IndicatorResult.success && topArticlesOk) {
      controller.finishRefresh(IndicatorResult.success);
    } else {
      controller.finishRefresh(IndicatorResult.fail);
    }
  }

  /// 上拉加载更多请求，页面值+1
  Future<void> loadMoreRequest() async {
    _pageIndex++;
    var articlesOk = await getArticlesList();
    controller.finishLoad(articlesOk);
  }

  /// 轮播图请求
  Future<bool> getBannerList() async {
    AppResponse<List<BannerBean>> bannerRes =
        await HttpGo.instance.get(Api.banner);
    bannerList.addAll(bannerRes.data ?? []);
    WanLog.d("轮播图长度: ${bannerRes.data?.length.toString()}");
    return bannerRes.isSuccessful;
  }

  ///置顶文章请求
  Future<bool> getTopArticlesList() async {
    AppResponse<List<ArticleBean>> topArticleRes =
        await HttpGo.instance.get(Api.topArticle);
    articleList.addAll(topArticleRes.data ?? []);
    return topArticleRes.isSuccessful;
  }

  /// 首页文章列表请求
  Future<IndicatorResult> getArticlesList() async {
    AppResponse<ArticleData> articleRes =
        await HttpGo.instance.get("${Api.homePageArticle}$_pageIndex/json");
    var list = articleRes.data?.datas ?? [];
    articleList.addAll(list);

    if (articleRes.isSuccessful) {
      if (list.isNotEmpty) {
        return IndicatorResult.success;
      } else {
        return IndicatorResult.noMore;
      }
    } else {
      return IndicatorResult.fail;
    }
  }
}
